<template>
  <div class="search-box">
    <!-- 筛选条件 -->
    <section class="category-box">
      <div class="breadcrumb knife_container">
        <!-- <router-link :to="{name: 'Index'}" class="bread_a">首页</router-link><i class="el-icon-arrow-right"></i> -->
        <span class="bread_a">全部结果</span> <i class="el-icon-arrow-right"></i>
         {{searchInput}}
         <el-tag size="mini" class="search-tags" v-for="(item, index) in searchTags" type="info" :key="index" v-if="item" @close="closeTag(index)" closable>{{item}}</el-tag>
         共
        <em class="color-red">{{amount}}</em>件商品
      </div>
    <div class="category-item knife_container">
      <div class="category-row" v-if="categoryList.length > 0">
        <span class="category-tit">商品类目</span>
        <section class="category-cont" :class="[collapseCate ? '':'isActive']">
          <div class="collose-tag collose-pos" v-if="cateHeight > 60" @click="collapseCate = !collapseCate">{{collapseCate ? '收起':'展开'}} <i :class="[collapseCate ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
          <div class="cont-item" ref="refCategory">
            <a v-for="(item, index) in categoryList" @click="clickCondi(item.id, 1)" :key="index" class="cont-item_a" :class="{'active': item.id === Number(categoryIds)}" :data-id="item.id" >
              {{item.name}}
            </a>
          </div>
        </section>
      </div>
      <!-- 品牌-->
      <div class="category-row" v-if="brandList.length > 0">
        <span class="category-tit">商品品牌</span>
        <section class="category-cont" :class="[collapseBrand ? '':'isActive']">
          <div class="collose-tag collose-pos" v-if="brandHeight > 80" @click="collapseBrand = !collapseBrand">{{collapseBrand ? '收起':'展开'}} <i :class="[collapseBrand ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
          <div class="cont-item brand-item" ref="refBrand" id="refBrand">
            <!-- {{brand.name}} -->
            <a class="cont-item_a" v-for="(brand, brandIndex) in brandList" :key="brandIndex" :data-id="brand.id"
            :class="{'active': brand.id === Number(brandIds)}" @click="clickCondi(brand.id, 0)">
            {{brand.name}}
              <!-- <img class="brand-img" :src="prefixImg + brand.image" :alt="brand.name"/> -->
            </a>
          </div>
        </section>
      </div>
      <!-- 属性 -->
      <div class="category-row" v-if="otherList.length > 0">
        <span class="category-tit">商品属性</span>
        <section class="category-cont" :class="[collapseOther ? '':'isActive']">
          <div class="collose-tag collose-pos" v-if="otherHeight > 60"  @click="collapseOther = !collapseOther">{{collapseOther ? '收起':'展开'}} <i :class="[collapseOther ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
          <div class="cont-item brand-item" ref="refProperty">
            <a class="cont-item_a" v-for="other in otherList" :key="other"
            :class="{'active': other === others}" @click="clickCondi(other, 2)">{{other}}</a>
          </div>
        </section>
      </div>
    </div>
  </section>
  <!-- 内容 -->
  <template v-if="!formatGoodsList.length">
    <div class="no-content">
      没有查到相关产品...
    </div>
  </template>
  <section class="search-content knife_container" v-if="searchType === 2">
    <ul class="list-wrapper">
      <li class="product-list-item goods-item-border" v-for="(goodsItem, goodsIndex) in formatGoodsList" :key="goodsIndex">
        <div class="goods-image">
          <router-link :to="{name: 'productDetail', params: {commodityID: goodsItem.goodsId}}">
            <img class="list-img" :src="prefixImg + goodsItem.image" :alt="goodsItem.detail" @error="catchErrorImage($event)">
          </router-link>
        </div>
        <div class="goods-info">
          <router-link
          :to="{name: 'productDetail', params: {commodityID: goodsItem.goodsId}}"class="goods-detail">
            <span v-html="goodsItem.detail"></span>
            <span class="activeTag" v-if="+goodsItem.activityId > 0">活动</span>
           </router-link>
          <router-link
            :to="{name: 'productDetail', params: {commodityID: goodsItem.goodsId}}"
           tag="p" class="goods-name" v-html="`${goodsItem.goodsName} ${goodsItem.brandName} ${goodsItem.other ? goodsItem.other : ''}`"></router-link>
          <div class="goods-price">
            <template v-if="loginStatus === 1">
              <span class="current-price">{{goodsItem.price}}元</span>
              <span class="old-price" v-if="+goodsItem.discountPrice > 0">￥{{goodsItem.discountPrice}}</span>
            </template>
            <span class="current-price" v-else-if="loginStatus === 4">登录后查看</span>
            <span class="current-price" v-else>审核通过后查看</span>
          </div>
        </div>

        <div class="goods-right-order">
          <div class="goods-stock">
            <div class="color-blue" v-if="goodsItem.stockLimit">
              (剩余库存{{goodsItem.stock}}件)
            </div>
            <div v-else-if="goodsItem.stock">有货</div>
            <div v-else>
              <span
                class="color-blue pointer"
                @click.prevent="showConsult(goodsItem)"
                v-if="goodsItem.consultStatus === 0"
              >（查询库存）</span>
              <span class="color-gray66" v-else>{{goodsItem.inventoryStatusDesc}}</span>
            </div>
          </div>
          <el-input-number
            class="goods-input-number"
            @keydown.110.native.prevent=""
            size="mini "
            :disabled="loginStatus !==1 "
            :key="goodsItem.id"
            v-model="goodsItem.number"
            :min="0"
            :max="goodsItem.personalLimited ? goodsItem.lastPersonalLimitNum : goodsItem.maxNum"
            :ref="'pro_' + goodsIndex"
            :step="goodsItem.packingNum"
            @change="limitProNum($event, goodsIndex, goodsItem.packingNum, goodsItem)"
            >
          </el-input-number>
          <el-button type="primary" size="medium" class="goods-btn-add" @click="addShopcart(goodsItem.id, goodsItem.number, goodsIndex)">加入采购清单</el-button>
          <div class="goods-right-packing" v-show="goodsItem.packingNum !== 1">
            包装数：{{goodsItem.packingNum}}
          </div>
        </div>
      </li>
    </ul>
    <!-- pagination -->
    <el-row v-if="goodsObj.page && goodsObj.page.totalPages > 1">
      <el-pagination class="page_box" background layout="total, prev, pager, next, ->" :current-page="goodsPro.page"
        :total="goodsObj.page.totalRecords | parseIntType" :page-size="goodsObj.page.pageSize | parseIntType" @current-change="handlePage" ></el-pagination>
    </el-row>
  </section>
  <section class="search-content knife_container" v-else>
    <ul class="list-wrapper">
      <li class="product-list-item goods-item-border" v-for="(goodsItem, goodsIndex) in formatGoodsList" :key="goodsIndex">
        <span class="discount-card" v-if="goodsItem.activity">{{goodsItem.discount ? `降${parseInt(100 - goodsItem.discount * 100)}个点` : '参与活动'}}</span>
        <div class="goods-image">
          <router-link
          :to="{name: 'productDetail', params: {commodityID: goodsItem.id}}">
            <img class="list-img" :src="prefixImg + goodsItem.image" :alt="goodsItem.name" @error="catchErrorImage($event)">
          </router-link>
        </div>
        <div class="goods-info">
          <router-link
           :to="{name: 'productDetail', params: {commodityID: goodsItem.id}}"
           class="goods-detail" v-html="goodsItem.name + ' ' + goodsItem.brandName + ' ' + goodsItem.other"></router-link>
          <p class="goods-name">共<span class="color-red">{{goodsItem.standardNumber}}款</span>型号</p>
          <div class="goods-price">
            <template v-if="loginStatus === 1">
              <span class="pro-price color-red">
                {{goodsItem.priceLowerLimit| floatPrices}}
                <template v-if="goodsItem.priceLowerLimit !== goodsItem.priceUpperLimit"> - {{goodsItem.priceUpperLimit | floatPrices}}</template>
                元
              </span>
            </template>
            <span class="pro-price smallfont color-red" v-else-if="loginStatus === 4">登录后查看</span>
            <span class="pro-price smallfont color-red" v-else>审核通过后查看</span>
          </div>
        </div>
        <div class="goods-right-order">
          <el-button type="primary" size="medium" class="goods-btn-add" @click="goToDetail(goodsItem.id)">查看详情</el-button>
        </div>
      </li>
    </ul>
    <!-- pagination -->
    <el-row v-if="goodsObj.page && goodsObj.page.totalPages > 1">
      <el-pagination class="page_box" background layout="total, prev, pager, next, ->" :current-page="goodsPro.page"
        :total="goodsObj.page.totalRecords | parseIntType" :page-size="goodsObj.page.pageSize | parseIntType" @current-change="handlePage" ></el-pagination>
    </el-row>
  </section>
  <!-- 咨询模块弹窗 -->
    <el-dialog :title="consultObj.name" :visible.sync="consultVisible" width="320px" center top="20vh">
      <!-- 内部弹窗 -->
      <el-dialog :visible.sync="consultVisibleInner" width= "320px" center append-to-body>
        <span>{{consultdata}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="hiddenDialog">确定</el-button>
        </span>
      </el-dialog>
      <div>
        <p style="line-height: 3;">规格:&nbsp;&nbsp;{{consultObj.originname}}</p>
        <el-input v-model="consultObj.consultNum" placeholder="请输入咨询的数量，最多输入4位" maxlength="4" @change="consultInput"></el-input>
        <p class="color-red" v-show="errorObj.status">{{errorObj.text}}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="consultStockFun">直接咨询</el-button>
        <el-button size="medium" type="primary" @click="consultStockFun(1)">咨询并加入购物车</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {eventBus} from '@/tool/events-bus'
import {getProSpecList, getProductListByKeyword, getGoodsListByKeyword, getCategoryListByKeyword, getBrandListByKeyword, getOtherListByKeyword, changeProNumber, consultStock} from '@/service/get-data'
import {stock, prefixImg} from '@/tool/index'
import {getCookie} from '@/config/mUntils'
import {Dialog, Form, FormItem, Button, Input, Col, Row, Tabs, Cascader, TabPane, Table, TableColumn, Pagination, InputNumber, Alert, Checkbox, Tag} from 'element-ui'
import {product} from '@/components/index'
import {mapActions, mapState} from 'vuex'
import _ from 'lodash'
export default {
  components: {
    elDialog: Dialog,
    elForm: Form,
    elFormItem: FormItem,
    elButton: Button,
    elInput: Input,
    elCol: Col,
    elRow: Row,
    elTabs: Tabs,
    elCascader: Cascader,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    elPagination: Pagination,
    elInputNumber: InputNumber,
    elAlert: Alert,
    elCheckbox: Checkbox,
    elTag: Tag,
    product
  },
  data () {
    return {
      collapseCate: false, // 分类是否展开
      collapseBrand: false, // 品牌是否展开
      collapseOther: false, // 其他属性是否展开
      consultVisible: false,
      consultVisibleInner: false, // 咨询内部的弹窗
      consultObj: {
        id: '', // 货品的id
        name: '', // 规格的名称
        packingNum: '', // 规格的包装数
        consultNum: '' // 咨询弹窗中 输入咨询的数量
      },
      consultdata: '', // 询货结果 null 询货中
      errorObj: { // 错误信息
        text: '请输入正确的数量,最多输入4位',
        status: false
      },
      increaseVisible: false, // 加入购物车弹窗
      increaseProNum: {
        proId: '', // 货品的id
        count: 1 // 添加货品的数量
      },
      proSpecList: {},
      // 规格列表
      searchPro: {
        name: '', // 获取规格列表的name值
        page: '1', // 获取规格列表的page值
        number: '10' // 获取规格列表的number值
      },
      goodsPro: {
        page: 1, // 商品列表的页码
        number: 20 // 商品列表一页的数量
      },
      searchType: Number(this.$route.query.searchtype) || 1, // 搜索类型 1商品 2规格
      isNew: false, // 新品
      isActive: false, // 活动中
      keyword: '',
      selectType: '', // 主选0为品牌，1为类目
      goodsObj: {}, // 商品列表
      formatGoodsList: [], // 格式化的list
      categoryList: [], // 类目列表
      categoryIds: '',
      brandList: [], // 品牌列表
      brandIds: '',
      amount: '',
      goodsId: '', // 获取规格商品的id
      otherList: [],
      others: '',
      brandHeight: '', // 品牌的高度
      cateHeight: '', // 类目的高度
      otherHeight: '', // 其他属性的高度
      searchedKey: ''
    }
  },
  computed: {
    ...mapState({
      previouskey: state => state.previouskey,
      username: state => state.user.username,
      shopcartId: state => state.shopcart.shopCartId,
      limitArr: state => state.shopcart.limitArr
    }),
    searchTags () {
      let arr1 = this.categoryList.filter((item) => {
        if (item.id === +this.categoryIds) {
          return true
        } else {
          return false
        }
      })
      let arr2 = this.brandList.filter((item) => {
        if (item.id === +this.brandIds) {
          return true
        } else {
          return false
        }
      })
      let arr3 = this.otherList.filter((item) => {
        if (item === this.others) {
          return true
        } else {
          return false
        }
      })
      let categoryname = arr1.length ? arr1[0].name : ''
      let brandname = arr2.length ? arr2[0].name : ''
      let othername = arr3.length ? arr3[0] : ''
      return [categoryname, brandname, othername]
    },
    authUserMethod () {
      if (!this.Token) {
        this.$confirm('此操作需要登录,是否前去登录', '提示').then(() => {
          this.$router.push({name: 'Login', query: { redirect: this.$route.fullPath }})
        }).catch(() => {
          console.log('未登录')
        })
        return false
      } else if (this.Exam === 3) {
        this.$store.commit('EXAMNODO', true)
        return false
      } else if (this.Exam === 2) {
        this.$store.commit('EXAMFAIL', true)
        return false
      } else if (this.Exam === 0) {
        this.$message.error('您的企业信息还在审核中,商品不能加入购物车,我们尽快给您审核.')
        return false
      } else {
        return true
      }
    },
    stock () {
      return stock
    },
    prefixImg () {
      return prefixImg
    },
    searchInput () {
      let route = this.$route.query
      return route.keyword
    },
    Token () {
      return getCookie('Token')
    },
    Exam () {
      return parseInt(getCookie('Exam'))
    },
    loginStatus () {
      return this.$store.getters.loginStatus
    }
  },
  methods: {
    ...mapActions(['fetchCartList']),
    catchErrorImage (e) {
      e.target.src = require('img/newload.png')
    },
    eventSearch () {
      let _this = this
      eventBus.$on('searchInput', function (val) {
        _this.keyword = val
        _this.brandIds = ''
        _this.categoryIds = ''
        _this.others = ''
        _this.getAllData()
      })
    },
    closeTag (index) {
      if (index === 0) {
        this.categoryIds = ''
      } else if (index === 1) {
        this.brandIds = ''
      } else {
        this.others = ''
      }
      this.$router.push({name: 'ModelList', query: {cateId: this.categoryIds, brandId: this.brandIds, searchtype: this.searchType, selectType: this.selectType, page: this.goodsPro.page, keyword: this.keyword, others: this.others}})
    },
    consultInput () {
      let step = this.consultObj.packingNum
      let leftNum = this.consultObj.consultNum
      let lastNum = leftNum % step
      this.consultObj.consultNum = lastNum === 0 ? leftNum : leftNum - lastNum + step
    },
    // 隐藏弹窗
    hiddenDialog () {
      this.consultObj.consultNum = '' // 询货数量清空
      this.consultVisible = false
      this.consultVisibleInner = false
    },
    // 限购购物车
    limitProNum (value, index, step, objitem) {
      this.formatGoodsList = [...this.formatGoodsList] // 强制vue监听变化
      this.debounceLimitProNum(value, index, step, objitem)
    },
    // 查看详情
    goToDetail (id) {
      this.$router.push({name: 'productDetail', params: {commodityID: id}})
    },
    // 刷新时的type 层级,typeid 搜索关键字 keyword
    initType () {
      let routequery = this.$route.query
      this.categoryIds = routequery.cateId
      this.brandIds = routequery.brandId
      this.selectType = routequery.selectType || ''
      this.keyword = routequery.keyword
      this.others = routequery.others
      this.goodsPro.page = routequery.page - 0 || 1
    },
    // 点击品牌或者分类
    clickCondi (id, type) {
      this.selectType = type
      type === 1 ? this.categoryIds = id : (type === 0 ? this.brandIds = id : this.others = id)
      this.goodsPro.page = 1 // 页码设置为1
      // this.getAllData()
      this.$router.push({name: 'ModelList', query: {cateId: this.categoryIds, brandId: this.brandIds, searchtype: this.searchType, selectType: this.selectType, page: this.goodsPro.page, keyword: this.keyword, others: this.others}})
    },
    getAllData (category, brand) {
      this.fetchGoodsListByKeyword()
      this.fetchCategoryList()
      this.fetchBrandList()
      this.fetchOtherListByKeyword()
    },
    // 关键字搜索商品
    async fetchGoodsListByKeyword () {
      console.log('请求库存')
      let isNewKeyword = this.searchInput !== this.previouskey && this.searchedKey !== this.searchInput
      let res
      if (this.searchType === 1) {
        res = await getGoodsListByKeyword(this.goodsPro.page, this.goodsPro.number, this.searchInput, this.categoryIds, this.brandIds, this.others, isNewKeyword, this.username)
      } else {
        res = await getProductListByKeyword(this.goodsPro.page, this.goodsPro.number, undefined, this.searchInput, this.categoryIds, this.brandIds, this.others, isNewKeyword, this.username)
      }
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.goodsObj = res.data
        this.changeColor(this.goodsObj.list)
        this.amount = res.data.page.totalRecords
        this.searchedKey = this.searchInput
      }
    },
    // 通过关键字获取类目列表
    async fetchCategoryList () {
      let res = await getCategoryListByKeyword(this.searchInput, this.brandIds, this.selectType, this.others)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.$nextTick(() => {
          this.categoryList = res.data
        })
      }
    },
    // 获取其他属性
    async fetchOtherListByKeyword () {
      let res = await getOtherListByKeyword(this.searchInput, this.categoryIds, this.brandIds, this.selectType)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.otherList = res.data
      }
    },
    // 通过关键字获取品牌列表
    async fetchBrandList () {
      let res = await getBrandListByKeyword(this.searchInput, this.categoryIds, this.selectType, this.others)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.brandList = res.data
      }
    },
    // 货品规格列表
    async fetchProSpecList () {
      let loadingSpec = this.$loading({target: '.commodity-desc'})
      let res = await getProSpecList(this.goodsId, this.searchPro.page, this.searchPro.number, this.searchPro.name)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        let len = res.data.list.length
        if (len <= 1) {
          this.sigleObj = res.data.list
        }
        this.proSpecList = res.data
        loadingSpec.close()
      } else {
        loadingSpec.close()
        this.message({
          message: '未获取规格列表'
        })
      }
    },
    // 商品列表分页
    handlePage (page) {
      this.goodsPro.page = page
      // this.$router.push({name: 'ModelList', query: {cateId: this.categoryIds, brandId: this.brandIds, selectType: this.selectType, page: this.goodsPro.page, keyword: this.keyword}})
      this.fetchGoodsListByKeyword()
      document.body.scrollTop = document.documentElement.scrollTop = 0
    },
    // 规格页码选择
    page (currentPage) {
      this.searchPro.page = currentPage
      this.fetchProSpecList()
    },
    showConsult (item) {
      const result = this.authUserMethod
      if (!result) return
      this.consultVisible = true
      this.consultObj.name = item.originname
      this.consultObj.id = item.id
      this.consultObj.packingNum = item.packingNum
      this.consultObj.consultNum = +item.packingNum
    },
    // 关键字高亮
    changeColor (resultsList) {
      resultsList.map((item, index) => {
        if (this.searchInput && this.searchInput.length > 0) {
          let replaceReg = new RegExp(this.searchInput, 'g')
          let repalceStr = `<span class="color-red">${this.searchInput}</span>`
          if (this.searchType === 2) {
            resultsList[index].originname = item.detail
            resultsList[index].detail = item.detail.replace(replaceReg, repalceStr)
            resultsList[index].goodsName = item.goodsName.replace(replaceReg, repalceStr)
            resultsList[index].brandName = item.brandName.replace(replaceReg, repalceStr)
          } else {
            resultsList[index].originname = item.name
            resultsList[index].name = item.name.replace(replaceReg, repalceStr)
            resultsList[index].other = item.other.replace(replaceReg, repalceStr)
            resultsList[index].brandName = item.brandName.replace(replaceReg, repalceStr)
          }
        }
        if (this.searchType === 2) { // 规格列表需要添加选购数量
          resultsList[index].maxNum = resultsList[index].stockLimit ? resultsList[index].stock : 9999
          resultsList[index].number = 0
        }
      })
      this.goodsObj.list = []
      this.goodsObj.list = resultsList
      this.formatGoodsList = [...resultsList]
    },
    debounceShopcart () {
      this.addShopcart = _.debounce(async function (id, number, skuIndex) {
        const result = this.authUserMethod
        if (!result || !number) return
        const vm = this
        let res = await changeProNumber(this.shopcartId, id, '', number, 0)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.formatGoodsList[skuIndex].number = 0
          this.$nextTick(() => {
            vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
          })
          this.fetchCartList() // 更新购物车列表
          // this.$message({message: '已经添加货品的数量到购物车'})
        } else {
          this.$message.error({
            message: res.data.resultMsg
          })
        }
      }, 300, {leading: true, trailing: false})
    },
    debounceProNum () {
      this.debounceLimitProNum = _.debounce(function (value, index, step, objitem) {
        let result = this.authUserMethod
        if (!result) {
          return false
        }
        if (value === 0) return
        let surplusNum // 去掉购物车数量的剩余可购买数量
        let shopcatNum = 0
        // 如果不存在id请求购物车
        if (!this.shopcartId) {
          this.fetchCartList()
          this.shopcartId = this.$store.state.shopcart.shopCartId
        }
        let lastNum = value % step
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        if (lastNum !== 0) {
          this.$message(`您当前选择的商品是${step}件一起采购哦`)
          // this.formatGoodsList[index].number = leftNum // 加入临时已选规格
          // return
        }

        // 个人限购 商品不限购
        if (objitem.personalLimited) {
          this.limitArr.map((limitItm, limitInd) => {
            if (objitem.id === limitItm.pid) {
              shopcatNum = limitItm.num
            }
          })
          surplusNum = objitem.lastPersonalLimitNum - shopcatNum
          // 购物存货和限购数量一样 或 个人限购剩余数量为0
          if (surplusNum === 0 || objitem.lastPersonalLimitNum === 0) {
            this.$nextTick(() => {
              this.$refs[`pro_${index}`][0].setCurrentValue(0)
            })
            this.$message(`抱歉,此商品限购期间每人限购${objitem.personalLimitNum}件,您已达此商品的添加上限`)
          // 输入数量大于可购数量
          } else if (surplusNum > 0 && leftNum > surplusNum) {
            if (objitem.stockLimit && surplusNum > objitem.stock) {
              this.$nextTick(() => {
                this.$refs[`pro_${index}`][0].setCurrentValue(objitem.stock)
                // this.temporaryCart[objitem.id].num = objitem.stock
                // this.$refs[`pro_${index}`].setCurrentValue(objitem.stock)
              })
              this.$message(`您的选购数量已达库存数量`)
              return
            } else {
              this.$nextTick(() => {
                this.$refs[`pro_${index}`][0].setCurrentValue(surplusNum)
                // this.temporaryCart[objitem.id].num = surplusNum
                // this.$refs[`pro_${index}`].setCurrentValue(surplusNum)
              })
              this.$message('您的选购数量已达上限')
              return
            }
          }
        }

        // 商品限购
        if (objitem.stockLimit && leftNum > objitem.stock) {
          this.$message('您的选购数量已达库存数量')
          this.$nextTick(() => {
            this.$refs[`pro_${index}`][0].setCurrentValue(objitem.stock)
          })
          leftNum = objitem.stock
        } else {
          this.$nextTick(() => {
            this.$refs[`pro_${index}`][0].setCurrentValue(leftNum)
            // this.temporaryCart[objitem.id].num = leftNum
            // this.$refs[`pro_${index}`].setCurrentValue(leftNum)
          })
        }
      }, 100, {leading: true, trailing: false})
    },
    // 咨询弹窗按钮 type 0 仅咨询 1 咨询并加入购物车
    async consultStockFun (type = 0) {
      let num = this.consultObj.consultNum
      let reg = /^\d{1,5}$/
      let result
      if (reg.test(num) && num !== 0) {
        this.errorObj.status = false
        this.errorObj.text = ''
        let res = await consultStock(this.consultObj.id, this.consultObj.consultNum)
        res = res.data
        if (res.resultCode && res.resultCode === 2000) {
          result = res.data
          if (type === 1 && result !== 0) {
            this.addToShop() // 加入购物车
          }
          this.fetchGoodsListByKeyword() // 规格列表重新请求
          this.showConsultText(type, result)
          this.consultVisible = false
        }
      } else {
        this.errorObj.text = '请输入正确的数量,最多输入4位'
        this.errorObj.status = true
      }
    },
    // 加入购物车 改变货品的数量
    async addToShop () {
      const result = this.authUserMethod
      if (!result) {
        return
      }
      let number = parseInt(this.consultObj.consultNum)
      if (!number) return
      if (number > 0) {
        if (!this.shopcartId) { // 如果不存在id 请求购物车
          this.fetchCartList()
        }
        let res = await changeProNumber(this.shopcartId, this.consultObj.id, '', number, 0)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.errorObj.status = false
          this.errorObj.text = ''
          this.fetchCartList() // 更新购物车列表
          this.consultVisible = false // 隐藏数量弹窗
          // this.$message({message: '已经添加货品的数量到购物车'})
          eventBus.$emit('show:pop')
        } else {
          this.$message.error({
            message: res.data.resultMsg
          })
        }
      }
    },
    // 咨询库存状态 文字显示
    showConsultText (type, result) {
      if (type === 1) {
        switch (result) {
          case 0: this.consultdata = '商品缺货,无法加入购物车'; break
          case 1: this.consultdata = '商品库存紧张,加入购物车后请尽快下单'; break
          case 2: this.consultdata = '商品库存正常,已成功加入购物车'; break
          case 3: this.consultdata = '商品库存充足,已成功加入购物车'; break
          default: this.consultdata = '商品库存正在咨询中,请到购物车查看库存库存状态'; break
        }
      } else {
        switch (result) {
          case 0: this.consultdata = '商品缺货'; break
          case 1: this.consultdata = '商品库存紧张'; break
          case 2: this.consultdata = '商品库存正常'; break
          case 3: this.consultdata = '商品库存充足'; break
          default: this.consultdata = '系统正在查询，您可以先浏览其他商品。'; break
        }
      }
    }
  },

  mounted () {
    this.initType()
    this.getAllData()
    this.debounceShopcart()
    this.debounceProNum()
  },
  watch: {
    '$route' (val) {
      this.searchType = Number(val.query.searchtype)
      this.initType()
      this.getAllData()
    },
    // 高度监测
    otherList () {
      this.$nextTick(() => {
        if (this.$refs.refProperty) {
          let height = this.$refs.refProperty.offsetHeight
          this.otherHeight = height
        }
      })
    },
    brandList () {
      this.$nextTick(() => {
        if (this.$refs.refBrand) {
          let height = this.$refs.refBrand.offsetHeight
          this.brandHeight = height
        }
      })
    },
    categoryList () {
      this.$nextTick(() => {
        if (this.$refs.refCategory) {
          let height = this.$refs.refCategory.offsetHeight
          this.cateHeight = height
        }
      })
    }
  },
  filters: {
    parseIntType (val) {
      return parseInt(val)
    }
  }
}
</script>

<style lang="scss" scoped>
  .active{
    color:#FFCC00;
  }
  .breadcrumb{
    color: #333;
  }
  .bread_a{
    position: relative;
    &:after{
      position: absolute;
      content: '';
      width: 30px;
      height: 3px;
      background: #FDAE3F;
      border-radius: 2px;
      bottom: -4px;
      left: 50%;
      margin-left: -15px;
    }
  }
  .search-tags{
    margin-left: 5px;
    color: #333333;
    border: none;
    background: none;
  }
  .activeTag{
    height:16px;
    line-height: 16px;
    vertical-align: middle;
    display: inline-block;
    border-radius:4px;
    border:1px solid rgba(255,115,0,1);
    font-size: 10px;
    padding: 0 3px;
    color: #FF7300;
  }
  .category-box {
      position: relative;
      margin-bottom: 20px;
      .category-row{
        overflow: hidden;
        // display: flex;
        border-bottom: 1px solid #e6e6e6;
        // justify-content: flex-start;
        transition: all 0.3s;
        background: #ececec;
      }

      .category-tit {
        // display: table-cell;
        background:#ececec;
        text-align: center;
        color: #858585;
        width:90px;
        line-height: 60px;
        font-size: 14px;
        float: left;
      }
      .category-cont{
        // display: table-cell;
        position: relative;
        // flex: 1;
        background: #fff;
        height: auto;
            margin-left: 90px;
      }
      .cont-item {
        // width: 1110px;
        //height: 60px;
        // line-height: 60px;
        border-bottom: 1px solid #e6e6e6;
        padding: 10px 150px 10px 0;
        &:last-child {
          border-bottom: none;
        }
      }
      .cont-item_a{
        color: #666;
        font-size: 14px;
        display: inline-block;
        padding: 13px 30px 13px 32px;
        &.active{
          color:#FFCC00;
        }
      }
      .brand-img{
        height: 30px;
        margin-right: 20px;
      }
       .isActive{
        height: 60px;
        overflow: hidden;
      }
    }
    .search-checkbox{
      width: 1190px;
      height: 60px;
      box-sizing: border-box;
      padding: 20px 30px;
      background-color: #fff;
      margin: 0 auto;
      font-size: 14px;
    }
    .collose-tag{
      font-size: 12px;
      color: #999;
      cursor: pointer;
      width: 60px;
      height: 30px;
      line-height: 30px;
      text-align: center;
    }
    .collose-pos{
      position: absolute;
      right: 10px;
      top: 15px;
    }
    // 搜索列表
    .search-content{
      margin-bottom: 50px;
      .pro-img{
        width: 60px;
        height: 60px;
        margin-right: 30px;
        margin-left: 18px;
      }
      .pro-name{
        font-size: 16px;
        color: #333;
        line-height: 22px;
      }
      .pro-amount{
        font-size: 12px;
        color: #666;
      }
      .brand{
        font-size:14px;
        color: #999;
      }
    }
    .shopcart{
      border-radius:4px;
      background: #ffcc00;
      text-align: center;
      color: #fff;
      font-size: 12px;
      line-height: 20px;
      display: inline-block;
      cursor: pointer;
      padding: 8px 22px;
      &:hover{
        color: #fff;
        background:rgba(255,204,0,.85);
      }
    }
    // 规格列表
    .search-div{
    width: 99%;
    box-sizing: border-box;
    position: relative;
    background: #FFFFFF;
    border: 2px solid #DCDCDC;
    border-radius: 4px;
    padding-left: 11px;
    height: 42px;
    line-height: 42px;
    font-size: 14px;
    margin-bottom: 17px;
    input{
      width: 95%;
    }
    i{
      position: absolute;
      float: right;
      @include fontbase(#666666, 22px, 1);
      right: 14px;
      top: 10px;
    }
  }
  .add-to-shop{
    @include fontbase(#ffffff, 12px, 20px);
    display: inline-block;
    cursor: pointer;
    padding: 5px 15px;
    background: #FFCC00;
    border-radius: 2px;
  }
    a{
    &:hover{
      color:#FFCC00;
    }
  }
  .discount-card{
    top: 0;
  }
  .product-list-item{
    font-size: 0;
    padding: 10px 20px 10px 30px;
    position: relative;
    height: 100px;
    margin-top: 10px;
    background: #fff;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;

    .goods-image{
      display: inline-block;
      vertical-align: top;
      width: 79px;
      height: 79px;
      border: 1px solid #e6e6e6;
      position: relative;
      img{
        width: 100%;
        // height: 90px;
      }
    }
    .goods-info{
      display: inline-block;
      vertical-align: top;
      width: 280px;
      margin: 0 120px 0 10px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      .goods-detail{
        display: block;
        font-size: 14px;
        color: #222;
        margin-top: 5px;
        height: 20px;
        line-height: 20px;
        overflow: hidden;
      }
      .goods-name{
        font-size: 12px;
        color: #888;
        margin: 5px 0;
      }
      .goods-price{
        display: inline-block;
        vertical-align: top;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        margin-top: 15px;
        font-size: 14px;
        .current-price{
          color: #f03a58;
          font-size: 16px;
        }
        .old-price{
          color: silver;
          font-size: 16px;
          text-decoration: line-through;
        }
      }
    }
    .goods-stock{
      display: inline-block;
      font-size: 14px;
      line-height: 16px;
      vertical-align: middle;
      margin-right: 20px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }
    .goods-right-order{
      float: right;
      position: relative;
      display: inline-block;
      vertical-align: top;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin-top: 25px;
      font-size: 14px;
    }
    .goods-input-number{
      width: 100px;
      margin-top: 3px;
      vertical-align: top;
    }
    .goods-btn-add{
      margin-left: 20px;
      color: #333;
    }
    .goods-right-packing{
      position: absolute;
      bottom: -18px;
      font-size: 12px;
      color: #B0B0B0;
      padding-left: 108px;
    }
  }
  .el-dialog--center .el-dialog__body {
    text-align: initial;
    padding: 0px 27px 20px;
  }
</style>
